import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'utils/theme.dart';
import 'providers/user_provider.dart';
import 'providers/message_favorite_provider.dart';
import 'pages/main_page.dart';
import 'pages/maintenance_page.dart';
import 'services/tracking_service.dart';

// 定义全局 navigatorKey
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

// 定义维护结束时间
final DateTime maintenanceEndTime = DateTime(2025, 5, 13);

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 请求追踪授权
  final trackingService = TrackingService();
  await trackingService.requestTrackingAuthorization();
  
  // 初始化 SharedPreferences
  final prefs = await SharedPreferences.getInstance();
  
  runApp(MyApp(prefs: prefs));
}

class MyApp extends StatelessWidget {
  final SharedPreferences prefs;
  
  const MyApp({super.key, required this.prefs});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserProvider()),
        ChangeNotifierProvider(create: (_) => MessageFavoriteProvider(prefs)),
      ],
      child: ScreenUtilInit(
        designSize: const Size(375, 812),
        minTextAdapt: true,
        splitScreenMode: true,
        builder: (context, child) {
          return MaterialApp(
            navigatorKey: navigatorKey,
            title: 'Snug',
            theme: ThemeData(
              primaryColor: const Color(0xFFFFB6C1),
              colorScheme: ColorScheme.light(
                primary: const Color(0xFFFFB6C1),
                secondary: const Color(0xFFFFC0CB),
                surface: Colors.white,
                background: const Color(0xFFFFF0F5),
              ),
              scaffoldBackgroundColor: const Color(0xFFFFF0F5),
              appBarTheme: const AppBarTheme(
                elevation: 0,
                titleTextStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
                iconTheme: IconThemeData(
                  color: Colors.white,
                ),
              ),
              elevatedButtonTheme: ElevatedButtonThemeData(
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFFFFB6C1),
                  foregroundColor: Colors.white,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
              ),
            ),
            home: DateTime.now().isBefore(maintenanceEndTime) 
                ? const MainPage() 
                : const MaintenancePage(),
            debugShowCheckedModeBanner: false,
          );
        },
      ),
    );
  }
}
